import { LoadingOutlined } from '@ant-design/icons';
import { Layout, App } from 'antd';
import React, { useState, useEffect, useRef, useMemo, useCallback, Suspense } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';

// import BasicInfo from './components/BasicInfo';
// import DialogSettings from './components/DialogSettings';
// import KnowledgeBase from './components/KnowledgeBase';
// import Chat from '../app-qa';
// 导入新增组件
// import Datasets from '../datasets';
// import ApiManage from '../api-manage';
// import ExtensionManage from '../extension-manage';
// import PermissionManage from '../permission-manage';
// import KnowledgeManage from '../knowledge-manage';
// import Report from '../report';
import metahumanService from '@/api/services/metahumanService';
import orchestrationService from '@/api/services/orchestrationService';
import { SetPoliciesReq } from '@/common';
import { AppStatusEnum, AppType, AppWorkbenchType, UserRoleEnum } from '@/common/app/constants';
import { PublishAppV2Req } from '@/common/types/app/app';
import { SvgIcon } from '@/components/icon';
import { CircleLoading } from '@/components/loading';
import NotData from '@/components/NotData';
import useWindowWidth from '@/hooks/event/use-window-width';
import usePermission from '@/hooks/event/usePermission';
import { useRouter } from '@/router/hooks';
import { useInitializeData, useWorkBench } from '@/store/configStore';
import { useMetahumanStore } from '@/store/metahumanStore';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useUserInfo } from '@/store/userStore';
import { StorageEnum } from '@/types/enum';
import { getItem } from '@/utils/storage';

import HistoryChat from '../history-chat';
import Share from '../share';

import Header, { HeaderRef } from './components/Header';
import HistoryVersions from './components/HistoryVersions';
import { useRequest } from 'ahooks';

const BasicInfo = React.lazy(() => import('./components/BasicInfo'));
const DialogSettings = React.lazy(() => import('./components/DialogSettings'));
const KnowledgeBase = React.lazy(() => import('./components/KnowledgeBase'));

const FusionSetting = React.lazy(() => import('./components/FusionAppSettings'));

const Chat = React.lazy(() => import('../app-qa'));
const Datasets = React.lazy(() => import('../datasets'));
const ApiManage = React.lazy(() => import('../api-manage'));
const ExtensionManage = React.lazy(() => import('../extension-manage'));
const PermissionManage = React.lazy(() => import('../permission-manage'));
const KnowledgeManage = React.lazy(() => import('../knowledge-manage'));
const Report = React.lazy(() => import('../report/index'));
const Report2 = React.lazy(() => import('../report/indexv2'));
const AppTest = React.lazy(() => import('../application-test'));

const AppPermissionContent = React.lazy(
  () => import('@/pages/app-permission-manage/components/AppPermissionContent'),
);

const { Content, Sider } = Layout;

type TabKey = 'basic' | 'dialog' | 'knowledge' | 'fusion';
type ContentType =
  | 'chat'
  | 'history'
  | 'datasets'
  | 'api-manage'
  | 'extension-manage'
  | 'permission-manage'
  | 'knowledge-manage'
  | 'report'
  | 'app-test'
  | 'share'
  | null;
type PermissionSubPageType = 'permission' | 'user' | 'role' | 'share' | 'qaPermission';
type KnowledgeSubPageType = 'datasets' | 'know-gov' | 'api' | 'extension' | 'nl2sql';

interface TabItem {
  key: TabKey;
  icon: string;
  label: string;
  status: string;
  component: React.ReactNode;
}

interface ContentChangeEvent {
  type: ContentType;
  id?: string;
  share_id?: string;
}

const AppOrchestration: React.FC<{
  isPreview?: boolean;
  id?: string;
  onApprove?: () => void;
  onReject?: () => void;
  onReturn?: () => void;
  previewBtn?: boolean;
}> = ({ isPreview = false, id, onApprove, onReject, onReturn, previewBtn }) => {
  const navigate = useNavigate();
  const location = useLocation();
  // const params = useParams<{ appId: string }>();
  const [activeTab, setActiveTab] = useState<TabKey>('dialog');
  const [isHistoryMode, setIsHistoryMode] = useState<boolean>(false);
  const [selectedVersion, setSelectedVersion] = useState<string | null>(null);
  const [activeNavKey, setActiveNavKey] = useState<string>('');
  const [contentType, setContentType] = useState<ContentType>(null);
  const [contentParams, setContentParams] = useState<{ id?: string; share_id?: string }>({});
  const [permissionSubPage, setPermissionSubPage] = useState<PermissionSubPageType>('qaPermission');
  const [knowledgeSubPage, setKnowledgeSubPage] = useState<KnowledgeSubPageType>('datasets');
  const headerRef = useRef<HeaderRef>(null);

  const [configurationsTemp, setConfigurationsTemp] = useState([]);
  const [noPermissionVisible, setNoPermissionVisible] = useState(false);

  const { isSuperAdmin } = usePermission();
  const router = useRouter();
  const workbench = useWorkBench();
  const { message } = App.useApp();
  const { isPc } = useWindowWidth();

  const [isKnowledgeFetching, setIsKnowledgeFetching] = useState(false);
  const [isSiderCollapsed, setIsSiderCollapsed] = useState(false);

  useEffect(() => {
    return () => {
      setUserRole([]);
      setAppDetail({});
      setVariables({});
      setConfigurationsTemp([]);
      setHotQuestions([]);
      setInputGuides([]);
      setAppLogo('');
      setSceneImage('');
      setFusionAppId('');
      setSubAppDetail(null);
      setAppDetailInit(null);
      setDatasetStats({
        count: 0,
        totalFiles: 0,
        apiCount: 0,
        appCount: 0,
      });
      reset();
    };
  }, []);

  const {
    virtualAvatarName,
    virtualAvatarVoice,
    setPermissionConfig,
    setIsPermissionConfigLoading,
    setVirtualAvatarEnabled,
    setVirtualAvatarId,
    setVirtualSpeakerId,
    setVirtualAvatarUrl,
    setVirtualAvatarName,
    setVirtualAvatarVoice,
    virtualAvatarEnabled,
    virtualAvatarId,
    virtualSpeakerId,
    permissionConfig: metahumanPermissionConfig,
    reset,
    stop,
    setAppId
  } = useMetahumanStore();

  const initializeData = useInitializeData();

  useEffect(() => {
    window.addEventListener('beforeunload', stop);
    return () => {
      console.log('卸载metahuman');
      window.removeEventListener('beforeunload', stop);
      stop()
      reset()
    }
  }, [])

  const { run: fetchMetahumanPermissionConfig } = useRequest(
    async (versionId?: string) => {
      const queryParams = new URLSearchParams(location.search);
      const appId = queryParams.get('appId') || id;
      if (!appId) return;
      setIsPermissionConfigLoading(true);
      try {
        const config = await metahumanService.getMetahumanPermissionConfig(
          appId,
          AppWorkbenchType.manage,
          versionId,
        );
        setPermissionConfig(config);
        setAppId(appId);
        setVirtualAvatarEnabled(config.metahumanEnabled);
        setVirtualAvatarId(config.avatarId);
        setVirtualSpeakerId(config.speakerId);
        setVirtualAvatarUrl(config.previewAvatarUrl);
        setVirtualAvatarName(config.avatarName || config.avatarId);
        setVirtualAvatarVoice(config.speakerName || config.speakerId);
        return config;
      } catch (error) {
        setPermissionConfig(null);
      } finally {
        setIsPermissionConfigLoading(false);
      }
    },
    {
      manual: true, // 需要手动触发
    },
  );

  useEffect(() => {
    // initializeData?.enableMetahuman 变化时重新拉取
    if (initializeData?.enableMetahuman) {
      fetchMetahumanPermissionConfig();
    }
  }, [initializeData?.enableMetahuman]);

  // useEffect(() => {
  //   const searchParams = new URLSearchParams(location.search);
  //   const app = searchParams.get('app') || '';
  //   if (app) {
  //     setActiveNavKey('knowledge-manage');
  //   } else {
  //     setActiveNavKey('orchestration');
  //   }
  // }, [location.search, setActiveNavKey]);

  const {
    setIsInOrchestrationPage,
    setAppDetail,
    special_app_lable,
    appDetail: appDetailStore,
    setVariables,
    appName,
    role_setup,
    task,
    opening_remarks,
    appDescription,
    appLogo,
    sceneImage,
    configurations,
    setHotQuestions,
    setInputGuides,
    setAppLogo,
    setSceneImage,
    datasetStats,
    setDatasetStats,
    setUserRole,
    userRole,
    setIsPreview: setStoreIsPreview,
    setShareId,
    setAppLogoList,
    setSceneImageList,
    reviewStatus,
    setFusionAppId,
    setSubAppDetail,
    isPublishTemplate,
    setAppDetailInit,
  } = useOrchestrationStore();
  const [loading, setLoading] = useState<boolean>(false);
  const [contentLoading, setContentLoading] = useState<boolean>(false);

  const userInfo = useUserInfo();
  const loginUserId = userInfo?._id || userInfo?.id;
  const isRoot = userInfo?.username == 'root';

  const [hasHandledNavType, setHasHandledNavType] = useState(false);

  const isConfigAvailable =
    configurations.length != 0 || appDetailStore?.appType != AppType.workflow;

  const isDisableDataset =
    configurations?.find((config) => config.name === 'disable_dataset')?.default_value === '1' ||
    false;

  const isEnableNl2sqlDataset =
    configurations?.find((config) => config.name === 'enable_nl2sql_dataset')?.default_value ===
      '1' || false;

  // 判断基础信息是否已设置
  const isBasicInfoSet = useMemo(() => {
    return appName && appName.length > 0;
    // return configurations?.some(config => config.name === 'app_name' && config.default_value)
  }, [configurations]);

  // 判断对话设置是否已设置
  const isDialogSettingsSet = useMemo(() => {
    if (!appDetailStore?.model) {
      return false;
    }
    return configurations?.every((config) => {
      if (
        config.type === 'input' &&
        !['app_logo', 'scene_image', 'app_name', 'app_description'].includes(config.name)
      ) {
        return config.default_value !== undefined && config.default_value !== '';
      }
      return true;
    });
  }, [configurations]);

  const isFusionFetching = useMemo(() => {
    return appDetailStore?.fusionApp?.length || 0 > 0;
  }, [appDetailStore]);

  // 判断知识库是否已设置
  const isKnowledgeBaseSet = useMemo(() => {
    return !(
      datasetStats.count === 0 &&
      datasetStats.apiCount === 0 &&
      datasetStats.appCount === 0
    );
  }, [datasetStats.count, datasetStats.apiCount, datasetStats.appCount]);

  // 检测当前路由，判断是否在编排页面
  useEffect(() => {
    const isOrchestrationPath = location.pathname.includes('/apps/orchestration');
    setIsInOrchestrationPage(isOrchestrationPath);
  }, [location.pathname, setIsInOrchestrationPage]);

  // 对历史消息和初始化状态的管理
  const [historyMessages, setHistoryMessages] = useState<any[]>([]);
  const [isChatInitialized, setIsChatInitialized] = useState(false);
  const [listLeft, setListLeft] = useState<any[]>([]);

  // const [appId, setAppId] = useState<string>('');
  const queryParams = new URLSearchParams(location.search);
  const appId = id || queryParams.get('appId') || '';
  const navType = id || queryParams.get('navType') || '';

  // 初始化预览状态和分享ID
  useEffect(() => {
    console.log('----初始化预览状态和分享ID');
    setStoreIsPreview(isPreview);
    const searchParams = new URLSearchParams(location.search);
    const shareId = searchParams.get('shareId');
    setShareId(shareId);
  }, [isPreview, location.search, setStoreIsPreview, setShareId]);

  // const fetchHotQuestions = async () => {
  //   if (!appId) return;
  //   try {
  //     const res = await orchestrationService.getAppHotIssue(appId);
  //     if (res.hot_issues) {
  //       // 转换HotIssue到HotQuestion
  //       const questions = res.hot_issues.map((issue, index) => ({
  //         id: String(index + 1),
  //         content: issue.content,
  //         answer: issue.answer
  //       }));
  //       // setHotTitle(questions);
  //       setHotQuestions(questions);
  //       // console.log('hotQuestions', res, res.hot_issues, questions)
  //     }
  //   } catch (error) {
  //     message.error('获取热门问题失败');
  //   }
  // };

  // useEffect(() => {
  //   fetchHotQuestions();
  // }, [appId]);

  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const app = searchParams.get('app') || '';
    const navType = searchParams.get('navType') || '';
    if (app || userRole == UserRoleEnum?.knowledge_manager) {
      setActiveNavKey('knowledge');
      headerRef.current?.switchToKnowledgeTab();
      setKnowledgeSubPage(app as KnowledgeSubPageType);
      setContentType('knowledge-manage');
    } else if (userRole == UserRoleEnum?.admin) {
      if (navType) {
        handleNavChange(navType, navType as ContentType);
      } else {
        setActiveNavKey('orchestration');
        setActiveTab('dialog');
        setContentType('chat');
      }
    }
  }, [location.search, setActiveNavKey, headerRef, setKnowledgeSubPage, setContentType, userRole]);

  // 初始化获取应用信息
  useEffect(() => {
    const fetchAppDetail = async () => {
      if (!appId) {
        // console.error('未获取到应用ID');
        // message.error('未获取到应用ID');
        return;
      }

      try {
        setLoading(true);
        setContentLoading(true);
        const appDetail = await orchestrationService.getAppDetailV2(appId, AppWorkbenchType.manage);

        if (appDetail?.review_status == AppStatusEnum.pending && !isPreview) {
          message.info('应用审核中，暂不支持编排');
        }

        // 更新 configurations 中的基础信息
        if (appDetail?.configurations) {
          const updatedConfigurations = appDetail.configurations.map((config) => {
            switch (config.name) {
              case 'app_name':
                return { ...config, default_value: appDetail.app_name || config.default_value };
              case 'app_description':
                return {
                  ...config,
                  default_value: appDetail.app_description || config.default_value,
                };
              case 'app_logo':
                return { ...config, default_value: appDetail.app_logo || config.default_value };
              case 'scene_image':
                return { ...config, default_value: appDetail.scene_image || config.default_value };
              default:
                return config;
            }
          });
          appDetail.configurations = updatedConfigurations;
        }
        setConfigurationsTemp(appDetail?.configurations || []);
        setAppDetail(appDetail);
        setAppDetailInit(appDetail);

        setShareId(appDetail?.share_id || null);

        // 设置用户权限
        if (appDetail.roles_for_user_in_app) {
          setUserRole(appDetail.roles_for_user_in_app);
        }

        const appImage = await orchestrationService.getAppImage(appId);
        if (appImage.logo) {
          setAppLogoList(appImage.logo);
        }
        if (appImage.scene) {
          setSceneImageList(appImage.scene);
        }
      } catch (error) {
        console.error('获取应用详情失败:', error);
        // message.error('获取应用详情失败');
      } finally {
        setLoading(false);
        setContentLoading(false);
      }
    };

    fetchAppDetail();
  }, [setAppDetail, setAppLogo, setSceneImage, setDatasetStats, isPreview, setShareId]);

  useEffect(() => {
    const fetchDatasetStats = async () => {
      if (appId) {
        try {
          setIsKnowledgeFetching(true);
          console.log('获取知识库统计数据');
          const datasets = await orchestrationService.getDatasetCount(appId);

          setDatasetStats(datasets);
        } catch (error) {
          console.error('获取知识库统计数据失败:', error);
        } finally {
          setIsKnowledgeFetching(false);
          console.log('获取知识库统计数据完成');
        }
      }
    };

    activeNavKey === 'orchestration' && fetchDatasetStats();
  }, [appId, setDatasetStats, activeNavKey]);

  // useEffect(() => {
  //   console.log('datasetStats', datasetStats)
  // }, [datasetStats])

  useEffect(() => {
    // 设置当前在编排页面
    setIsInOrchestrationPage(true);

    // 组件卸载时重置状态
    return () => {
      setIsInOrchestrationPage(false);
    };
  }, [setIsInOrchestrationPage]);

  // 切换到知识管理Tab并显示指定组件
  const switchToKnowledgeTabWithComponent = useCallback(
    (componentType: 'datasets' | 'api-manage' | 'extension-manage' | 'nl2sql-manage') => {
      // 切换到知识管理Tab
      setActiveNavKey('knowledge');
      // 确保Header组件的导航标签也同步更新
      headerRef.current?.switchToKnowledgeTab();

      // 根据组件类型设置相应的知识子页面
      if (componentType === 'datasets') {
        setKnowledgeSubPage('datasets');
      } else if (componentType === 'api-manage') {
        setKnowledgeSubPage('api');
      } else if (componentType === 'extension-manage') {
        setKnowledgeSubPage('extension');
      } else if (componentType === 'nl2sql-manage') {
        setKnowledgeSubPage('nl2sql');
      }

      // 设置要显示的组件类型
      setContentType('knowledge-manage');
    },
    [headerRef],
  );

  // 使用useMemo缓存tabs数组，避免每次渲染都创建新的组件实例
  const tabs = useMemo<TabItem[]>(() => {
    const allTabs: TabItem[] = [
      {
        key: 'basic',
        // icon: 'ic_baseinfo',
        // icon: 'information',
        icon: 'ai-orch-base',
        label: '基础信息',
        status: isBasicInfoSet ? '已设置' : '未设置',
        component: (
          <BasicInfo
            isPreview={isPreview || appDetailStore?.review_status == AppStatusEnum.pending}
            className="max-h-[calc(100vh-230px)]"
          />
        ),
      },
      {
        key: 'dialog',
        // icon: 'ic_chat_setting',
        // icon: 'dialogue',
        icon: 'ai-orch-dialog',
        label: '对话设置',
        status: isDialogSettingsSet ? '已设置' : '未设置',
        component: (
          <DialogSettings
            isPreview={isPreview || appDetailStore?.review_status == AppStatusEnum.pending}
          />
        ),
      },
      // {
      //   key: 'knowledge',
      //   icon: 'knowledge',
      //   label: '知识库',
      //   status: isKnowledgeFetching ? '' : isKnowledgeBaseSet ? '已设置' : '未设置',
      //   component: (
      //     <KnowledgeBase
      //       isPreview={isPreview}
      //       onSwitchToKnowledgeTab={switchToKnowledgeTabWithComponent}
      //     />
      //   ),
      // },
    ];

    const knowledgeTab = {
      key: 'knowledge',
      // icon: 'ic_dataset',
      // icon: 'knowledge',
      icon: 'ai-orch-dataset',
      label: '知识库',
      status: isKnowledgeFetching ? '' : isKnowledgeBaseSet ? '已设置' : '未设置',
      component: (
        <KnowledgeBase
          isPreview={isPreview || appDetailStore?.review_status == AppStatusEnum.pending}
          onSwitchToKnowledgeTab={switchToKnowledgeTabWithComponent}
        />
      ),
    };

    const fusionTab = {
      key: 'fusion',
      // icon: 'knowledge',
      icon: 'ai-orch-fusion',
      label: '融合应用',
      status: isFusionFetching ? '已设置' : '未设置',
      component: <FusionSetting />,
    };

    // 新增逻辑：从本地缓存读取天工角色状态
    const userInfo_tiangong = getItem<any>(StorageEnum.User);
    const isTiangongManager = Boolean(
      userInfo_tiangong?.is_TianGong === 'true' || userInfo_tiangong?.is_TianGong === true,
    );
    if (isTiangongManager) {
      // 天工角色，直接返回基础和对话设置
      return allTabs;
    }

    if (!userRole) {
      return [];
    }

    // 如果不是管理员，只显示知识库标签
    if (userRole == UserRoleEnum?.knowledge_manager && !isPreview) {
      // return allTabs.filter((tab) => tab.key === 'knowledge');
      return isDisableDataset ? [] : [knowledgeTab];
    }

    // 知识审核员，不显示任何标签
    if (userRole == UserRoleEnum?.knowledge_reviewer && !isPreview) {
      return [];
    }

    if (appDetailStore?.appType == AppType.fusion) {
      return [...allTabs, fusionTab];
    }

    return isDisableDataset ? [...allTabs] : [...allTabs, knowledgeTab];
  }, [
    isBasicInfoSet,
    isDialogSettingsSet,
    isKnowledgeBaseSet,
    isFusionFetching,
    switchToKnowledgeTabWithComponent,
    userRole,
    isPreview,
    isKnowledgeFetching,
    isDisableDataset,
    appDetailStore,
  ]);

  const handleTabChange = (key: TabKey) => {
    setActiveTab(key);
  };

  const toggleHistoryMode = async () => {
    const queryParams = new URLSearchParams(location.search);
    // const appId = queryParams.get('appId') || id;
    if (!appId) {
      // message.error('未获取到应用ID');
      return;
    }
    try {
      setIsHistoryMode(!isHistoryMode);
      setSelectedVersion(null);
    } catch (error) {
      // message.error('获取历史版本失败');
    }
  };

  const handleRestoreVersion = async (versionId: string) => {
    console.log('恢复到选定版本', versionId);
    setIsHistoryMode(false);

    fetchMetahumanPermissionConfig(versionId);

    const appDetail = await orchestrationService.getAppDetailV2(
      appId,
      AppWorkbenchType.manage,
      versionId,
    );
    if (appDetail?.configurations) {
      const updatedConfigurations = appDetail.configurations.map((config) => {
        switch (config.name) {
          case 'app_name':
            return { ...config, default_value: appDetail.app_name || config.default_value };
          case 'app_description':
            return { ...config, default_value: appDetail.app_description || config.default_value };
          case 'app_logo':
            return { ...config, default_value: appDetail.app_logo || config.default_value };
          case 'scene_image':
            return { ...config, default_value: appDetail.scene_image || config.default_value };
          default:
            return config;
        }
      });
      appDetail.configurations = updatedConfigurations;
    }
    setConfigurationsTemp(appDetail?.configurations || []);
    setAppDetail(appDetail);
    setAppDetailInit(appDetail);
  };

  const handleSelectVersion = (versionId: string) => {
    setSelectedVersion(versionId);
  };

  const handleNavChange = (
    key: string,
    componentType: ContentType,
    permissionSubPage?: PermissionSubPageType,
    knowledgeSubPage?: KnowledgeSubPageType,
  ) => {
    setActiveNavKey(key);

    console.log('切换到子页面', key);

    if (key === 'orchestration') {
      // 如果是编排，保持在当前页面显示编排界面
      setContentType('chat');
      return;
    }

    // 权限管理菜单点击时，设置子页面
    if (componentType === 'permission-manage') {
      setPermissionSubPage(permissionSubPage || 'qaPermission');
    }

    // 知识管理菜单点击时，设置子页面
    if (componentType === 'knowledge-manage') {
      setKnowledgeSubPage(knowledgeSubPage || 'datasets');
    }

    // 根据导航key设置内容类型
    setContentType(componentType);
  };

  // 处理权限管理子页面变更
  const handlePermissionSubPageChange = (subPage: PermissionSubPageType) => {
    setPermissionSubPage(subPage);
  };

  // 处理知识管理子页面变更
  const handleKnowledgeSubPageChange = (subPage: KnowledgeSubPageType) => {
    setKnowledgeSubPage(subPage);
  };

  const getTabStyle = (key: TabKey) => {
    const isActive = activeTab === key;
    return {
      cursor: 'pointer',
      padding: '8px 0',
      // background: isActive ? `${colorPrimary}1A` : colorBgBase,
      background: isActive ? 'white' : 'unset',
      // color: isActive ? colorPrimary : colorTextBase,
      // color: colorPrimary,
      borderRadius: '4px',
      display: 'flex',
      flexDirection: 'column' as const,
      gap: '4px',
      flex: 1,
      transition: 'all 0.3s',
    };
  };

  const handleSiderToggle = () => {
    setIsSiderCollapsed(!isSiderCollapsed);
  };

  // 渲染当前内容区域
  const renderContent = () => {
    switch (contentType) {
      case 'chat':
        return <Chat />;
      case 'history':
        return <HistoryChat />;
      case 'datasets':
        return <Datasets />;
      case 'api-manage':
        return <ApiManage />;
      case 'extension-manage':
        return <ExtensionManage />;
      case 'permission-manage':
        return (
          <PermissionManage
            subPage={permissionSubPage}
            onPageChange={handlePermissionSubPageChange}
          />
        );
      // case 'permission-manage':
      //   return (
      //     <AppPermissionContent
      //       appId={appId}
      //       isPreview={isPreview}
      //       createUserId={{ create_user_id: createUserId }}
      //       isPermissions={loginUserId != createUserId && !isRoot}
      //     />
      //   );
      case 'knowledge-manage':
        return (
          <KnowledgeManage
            subPage={knowledgeSubPage}
            onPageChange={handleKnowledgeSubPageChange}
            appType={appDetailStore?.appType}
          />
        );
      case 'report':
        return special_app_lable == '招生助手' ? <Report2 /> : <Report renderTitle={renderTitle} />;
      case 'app-test':
        return <AppTest />;
      case 'share':
        return <Share />;
      default:
        return loading ? (
          <CircleLoading />
        ) : (
          <div className="flex h-full items-center justify-center">
            <NotData />
          </div>
        );
    }
  };

  // 渲染头部信息
  const renderTitle = () => {
    switch (contentType) {
      case 'chat':
        return <Chat />;
      case 'history':
        return <HistoryChat />;
      case 'datasets':
        return <Datasets />;
      case 'api-manage':
        return <ApiManage />;
      case 'extension-manage':
        return <ExtensionManage />;
      case 'permission-manage':
        return (
          <PermissionManage
            subPage={permissionSubPage}
            onPageChange={handlePermissionSubPageChange}
          />
        );
      case 'knowledge-manage':
        return (
          <KnowledgeManage subPage={knowledgeSubPage} onPageChange={handleKnowledgeSubPageChange} />
        );
      case 'report':
        return '对话看板';
      default:
        return loading ? (
          <CircleLoading />
        ) : (
          <div className="flex h-full items-center justify-center">
            <NotData />
          </div>
        );
    }
  };

  const checkTabStatus = () => {
    const tabKeys = tabs.map((tab) => tab.key);
    for (const tabKey of tabKeys) {
      if (tabKey === 'basic' && !isBasicInfoSet) {
        message.warning('基础信息未设置');
        return false;
      }
      if (tabKey === 'dialog' && !isDialogSettingsSet) {
        message.warning('对话设置未设置');
        return false;
      }
      // if (tabKey === 'knowledge' && !isKnowledgeBaseSet) {
      //   message.warning('知识库未设置');
      //   return false;
      // }
      // if (tabKey === 'fusion' && !isFusionFetching) {
      //   message.warning('融合应用未设置');
      //   return false;
      // }
    }
    return true;
  };

  // 保存编排配置，调用发布接口
  const handleSave = async (
    is_publish = false,
    permissionConfig: SetPoliciesReq['statements'] = [],
    is_all_can_qa = false,
    is_auto_save = false,
  ): Promise<void> => {
    if (appDetailStore?.review_status == AppStatusEnum.pending) {
      message.info('应用审核中，暂不支持重新发布');
      return;
    }
    const queryParams = new URLSearchParams(location.search);
    const appId = queryParams.get('appId') || id;
    if (!appId) {
      message.warning('获取应用ID失败');
      return;
    }

    if (!configurations.find((config) => config.name === 'app_name')?.default_value && !appName) {
      message.warning('应用名称不能为空');
      return;
    }

    const baseInfo = {
      app_name:
        configurations.find((config) => config.name === 'app_name')?.default_value || appName,
      tag:
        configurations.find((config) => config.name === 'tag')?.default_value ||
        appDetailStore?.tag,
      app_description:
        configurations.find((config) => config.name === 'app_description')?.default_value ||
        appDescription ||
        '',
      app_logo:
        configurations.find((config) => config.name === 'app_logo')?.default_value ||
        appLogo ||
        'default',
      scene_image:
        configurations.find((config) => config.name === 'scene_image')?.default_value ||
        sceneImage ||
        '',
      fusionApp: appDetailStore?.fusionApp,
      model: appDetailStore?.model,
      isPublishTemplate,
      metahumanConfig:
        metahumanPermissionConfig?.metahumanPermission && virtualAvatarId && virtualSpeakerId
          ? {
              metahumanEnabled: virtualAvatarEnabled,
              avatarId: virtualAvatarId,
              speakerId: virtualSpeakerId,
            }
          : {},
    };

    const customConfigurations = configurations.map((config) => ({
      ...config,
      default_value:
        typeof config.default_value === 'boolean'
          ? config.default_value
            ? '1'
            : '0'
          : String(config.default_value),
    }));

    const params: PublishAppV2Req = {
      is_publish,
      is_all_can_qa,
      version_name: '',
      configurations: customConfigurations,
      permission_config: permissionConfig,
      ...baseInfo,
    };
    try {
      setLoading(true);
      console.log('customConfigurations', customConfigurations);

      if (is_publish && appDetailStore?.appType != AppType.fusion) {
        // await datasetService.knowledgeBasePublish({ app_id: appId });
        if (userRole !== UserRoleEnum.admin) {
          // message.success('知识库发布成功');
          return;
        }
      }

      if (userRole === UserRoleEnum.admin) {
        if (is_publish && appDetailStore?.appType == AppType.fusion) {
          if (!appDetailStore?.model) {
            message.warning('对话模型未选择');
            return;
          }
          // if (!appDetailStore?.fusionApp || appDetailStore?.fusionApp?.length == 0) {
          //   message.warning('融合应用未选择');
          //   return
          // }
        }

        if (metahumanPermissionConfig?.metahumanPermission && virtualAvatarId && virtualSpeakerId) {
          metahumanService.updateMetahumanPermissionConfig(appId, {
            metahumanEnabled: virtualAvatarEnabled,
            avatarId: virtualAvatarId,
            speakerId: virtualSpeakerId,
          });
        }

        await orchestrationService.appPublishV2(params, appId);
        const appDetail = await orchestrationService.getAppDetailV2(appId, AppWorkbenchType.manage);
        setAppDetail(appDetail);
        setAppDetailInit(appDetail);
      }

      setConfigurationsTemp(customConfigurations);
      // message.success(is_publish ? '发布成功' : '保存成功');

      if (is_publish) {
        if (isSuperAdmin || reviewStatus == AppStatusEnum?.pass) {
          message.success('发布成功');
        } else {
          message.success('发送管理员审核，审核通过后可使用');
        }
        router.push(workbench);
      } else {
        message.success(is_auto_save ? '自动保存成功' : '保存成功');
      }
    } catch (error) {
      console.error(is_publish ? '发布失败:' : '保存失败:', error);
      message.error(is_publish ? '发布失败' : '保存失败');
    } finally {
      setLoading(false);
    }
  };

  // 根据用户权限设置默认选中的标签
  useEffect(() => {
    if (userRole && userRole !== 'admin' && !isPreview) {
      setActiveTab('knowledge');
    }
  }, [userRole]);

  return (
    <Layout className="h-screen" style={{ minWidth: '1250px' }}>
      <Header
        ref={headerRef}
        activeType={activeNavKey}
        isHistoryMode={isHistoryMode}
        onToggleHistoryMode={toggleHistoryMode}
        onRestoreVersion={handleRestoreVersion}
        onSave={handleSave}
        onCheckTabStatus={checkTabStatus}
        onNavChange={handleNavChange}
        selectedHistoryVersion={selectedVersion}
        configurationsTemp={configurationsTemp}
        isPreview={isPreview}
        onApprove={onApprove}
        onReject={onReject}
        onReturn={onReturn}
        previewBtn={previewBtn}
      />
      <Suspense fallback={<CircleLoading />}>
        <Layout>
          {activeNavKey === 'orchestration' ? (
            <>
              {tabs?.length > 0 && (
                <Sider
                  width="33%"
                  className={`m-2 mr-1 rounded-[12px] border border-[transparent] !bg-[#fff] bg-white transition-all duration-300 ${
                    isSiderCollapsed
                      ? '!min-w-0 !max-w-0 overflow-hidden !bg-[transparent]'
                      : '!min-w-[350px] !max-w-[600px] !bg-[#fff]'
                  }`}
                  collapsed={isSiderCollapsed}
                  collapsedWidth={0}
                  trigger={null}
                >
                  {isConfigAvailable && tabs?.length > 0 && (
                    <div className="p-4" style={{ height: 'calc(100vh - 170px)' }}>
                      <div className="mb-4 flex gap-2 rounded-[6px] bg-[#F3F5F9] p-1">
                        {tabs.map((tab) => (
                          <div
                            key={tab.key}
                            style={getTabStyle(tab.key)}
                            onClick={() => handleTabChange(tab.key)}
                          >
                            <div className="flex flex-col items-center gap-1">
                              <span
                                className={`text-[12px] ${
                                  tab.status === '未设置' ? 'text-[#F53F3F]' : 'text-[#86909C]'
                                }`}
                              >
                                {tab.status ? (
                                  tab.status === '未设置' ? (
                                    tab.key === activeTab ? (
                                      <SvgIcon
                                        icon={`${tab.icon}-focus`}
                                        style={{ fontSize: '20px' }}
                                      />
                                    ) : (
                                      <SvgIcon
                                        icon={`${tab.icon}-unset`}
                                        style={{ fontSize: '20px' }}
                                      />
                                    )
                                  ) : (
                                    <SvgIcon
                                      icon={`${tab.icon}-set`}
                                      style={{ fontSize: '20px' }}
                                    />
                                  )
                                ) : (
                                  <LoadingOutlined style={{ fontSize: '20px' }} />
                                )}
                              </span>
                              <div>
                                <span
                                  className={`text-[14px] font-normal ${
                                    tab.status === '已设置' || tab.key === activeTab
                                      ? 'text-[#1B6DFA]'
                                      : 'text-[#4E5969]'
                                  }`}
                                >
                                  {tab.label}
                                </span>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                      {/* <div className="my-4 border-t border-[#011B4614]"></div> */}
                      <Suspense fallback={<CircleLoading />}>
                        {tabs.find((tab) => tab.key === activeTab)?.component}
                      </Suspense>
                    </div>
                  )}
                </Sider>
              )}
              <Content
                className="m-2 ml-1 rounded-[12px]"
                style={{
                  height: 'calc(100vh - 80px)',
                  position: 'relative',
                }}
              >
                {/* <div
                  className="absolute left-[-10px] top-[8px] z-10"
                >
                  <div
                    onClick={handleSiderToggle}
                    className="border-border bg-bg-paper absolute -right-1 top-4 z-50 hidden translate-x-1/2 cursor-pointer select-none  md:flex"
                  >
                    {isSiderCollapsed ? (
                      <SvgIcon icon="ai-orch-expand" size={70} />
                    ) : (
                      <SvgIcon icon="ai-orch-collapse" size={70} />
                    )}
                  </div>
                </div> */}
                <Suspense fallback={<CircleLoading />}>
                  <>
                    {isPc && (
                      <div className="absolute left-[-10px] top-[8px] z-10">
                        <div
                          onClick={handleSiderToggle}
                          className="border-border bg-bg-paper absolute -right-1 top-4 z-50 hidden translate-x-1/2 cursor-pointer select-none  md:flex"
                        >
                          {isSiderCollapsed ? (
                            <SvgIcon icon="ai-orch-expand" size={70} />
                          ) : (
                            <SvgIcon icon="ai-orch-collapse" size={70} />
                          )}
                        </div>
                      </div>
                    )}
                    {renderContent()}
                  </>
                </Suspense>
              </Content>

              {isHistoryMode && (
                <div className="m-2 w-[280px]">
                  <HistoryVersions
                    onRestore={handleSelectVersion}
                    onSelectVersion={(version) => {
                      setSelectedVersion(version);
                    }}
                  />
                </div>
              )}
            </>
          ) : (
            <div className="flex flex-1">
              <Content
                className="m-2 flex-1 overflow-hidden rounded-xl"
                style={{
                  // background: '#FFFFFF',
                  position: 'relative',
                  height: 'calc(100vh - 80px)', // 减去头部高度和边距
                }}
              >
                {renderContent()}
              </Content>

              {isHistoryMode && (
                <div className="m-2 w-[280px]">
                  <HistoryVersions
                    onRestore={handleSelectVersion}
                    onSelectVersion={(version) => {
                      setSelectedVersion(version);
                    }}
                  />
                </div>
              )}
            </div>
          )}
        </Layout>
      </Suspense>
    </Layout>
  );
};

export default AppOrchestration;
